/**
 * Copyright (c) 2005-2012 springside.org.cn
 */
package com.sinosoft.hydra.um.utils;

import com.alibaba.druid.filter.config.ConfigTools;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringEscapeUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;

/**
 * 封装各种格式的编码解码工具类.
 * 1.Commons-Codec的 hex/base64 编码
 * 2.自制的base62 编码
 * 3.Commons-Lang的xml/html escape
 * 4.JDK提供的URLEncoder
 *
 * @author calvin
 * @version 2013-01-15
 */
public class Encodes {

    private static final String DEFAULT_URL_ENCODING = "UTF-8";
    private static final char[] BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
    private static final byte[] ATTACHMENT_DES_KEY = {-45, -56, 25, 69, 62, -5, 69, 65, 17, -26, 32, 56, -26, -123, -67, 69};

    static byte[] keyiv;
    static byte[] keyPs;

    static {
        try {
            keyiv = "4*#yA5$,H".getBytes("UTF-8");
            keyPs = "1$2%3^u(&6R$yh&N".getBytes("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Hex编码.
     */
    public static String encodeHex(byte[] input) {
        return new String(Hex.encodeHex(input));
    }

    /**
     * descbc加密数组
     *
     * @param content 数组
     * @return
     */
    public static byte[] desCbcEncrypt(byte[] content) {
        DESKeySpec keySpec = null;
        byte[] result = null;
        try {
            keySpec = new DESKeySpec(ATTACHMENT_DES_KEY);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(keySpec);
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            byte[] key1 = keySpec.getKey();
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(key1));
            result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
            System.out.println("加密出错");
            System.out.println(e.getMessage());
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        String db = "";
        for(String aa : args){
            if(Arrays.asList("0", "1", "2").contains(aa)){
                db = aa;
            }else{
                if("0".equals(db)){
                    System.out.println("生成数据库编码");
                    String[] arr = ConfigTools.genKeyPair(512);
                    System.out.println("src:");
                    System.out.println(aa);
                    System.out.println("dest:");
                    System.out.println(ConfigTools.encrypt(arr[0], aa));
                    System.out.println("publickey:");
                    System.out.println(arr[1]);
                }
                if("1".equals(db)){
                    System.out.println("生成常用编码");
                    System.out.println("src:");
                    System.out.println(aa);
                    System.out.println("dest:");
                    System.out.println(getEncodeDes(aa));
                }
                if("2".equals(db)){
                    System.out.println("生成密钥编码");
                    System.out.println("src:");
                    System.out.println(aa);
                    System.out.println("dest:");
                    System.out.println(getEncode(aa));
                }
            }
        }
    }

    /**
     * descbc加密字符串
     *
     * @param str 原始字符串
     * @return
     */
    public static String getEncodeDes(String str) {
        try {
            return encodeHex(desCbcEncrypt(str.getBytes(DEFAULT_URL_ENCODING)));
        } catch (UnsupportedEncodingException e) {
            throw Exceptions.unchecked(e);
        }
    }

    public static String getDecode(String encode) {
        try {
            return new String(new BASE64Decoder().decodeBuffer(encode.substring(4)), "utf-8").substring(7, 23);
        } catch (Exception e) {

        }
        return null;
    }

    public static String getEncode(String value) {
        if (value.length() < 16) {
            value = ("" + value + value + value + value + value + value + value + value).substring(0, 16);
        } else if (value.length() > 16) {
            value = value.substring(0, 16);
        }
//		System.out.println(value);
        StringBuffer sb = new StringBuffer();
        sb.append(value.charAt(0));
        sb.append(value.charAt(1));
        sb.append(value.charAt(3));
        sb.append(value.charAt(5));
        sb.append(value.charAt(2));
        sb.append(value.charAt(4));
        sb.append(value.charAt(6));
        sb.append(value);
        sb.append(value.charAt(7));
        sb.append(value.charAt(9));
        sb.append(value.charAt(11));
        sb.append(value.charAt(13));
        sb.append(value.charAt(15));
        sb.append(value.charAt(10));
        sb.append(value.charAt(12));
        sb.append(value.charAt(14));
        return "TRLT" + new BASE64Encoder().encode(sb.toString().getBytes());
    }

    /**
     * descbc解密数组
     *
     * @param content
     * @return
     */
    public static byte[] desCbcDecrypt(byte[] content) {
        DESKeySpec keySpec = null;
        byte[] result = null;
        try {
            keySpec = new DESKeySpec(ATTACHMENT_DES_KEY);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(keySpec);
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(keySpec.getKey()));
            result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
            System.out.println("解密出错");
            System.out.println(e.getMessage());
        }
        return result;
    }

    /**
     * descbc解密字符串
     *
     * @param str 加密字符串
     * @return
     */
    public static String getDecodeDes(String str) {
        try {
            return new String(desCbcDecrypt(decodeHex(str)), DEFAULT_URL_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw Exceptions.unchecked(e);
        }
    }

    /**
     * Hex解码.
     */
    public static byte[] decodeHex(String input) {
        try {
            return Hex.decodeHex(input.toCharArray());
        } catch (DecoderException e) {
            throw Exceptions.unchecked(e);
        }
    }

    /**
     * Base64编码.
     */
    public static String encodeBase64(byte[] input) {
        return new String(Base64.encodeBase64(input));
    }

    /**
     * Base64编码.
     */
    public static String encodeBase64(String input) {
        try {
            return new String(Base64.encodeBase64(input.getBytes(DEFAULT_URL_ENCODING)));
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

//	/**
//	 * Base64编码, URL安全(将Base64中的URL非法字符'+'和'/'转为'-'和'_', 见RFC3548).
//	 */
//	public static String encodeUrlSafeBase64(byte[] input) {
//		return Base64.encodeBase64URLSafe(input);
//	}

    /**
     * Base64解码.
     */
    public static byte[] decodeBase64(String input) {
        return Base64.decodeBase64(input.getBytes());
    }

    /**
     * Base64解码.
     */
    public static String decodeBase64String(String input) {
        try {
            return new String(Base64.decodeBase64(input.getBytes()), DEFAULT_URL_ENCODING);
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    /**
     * Base62编码。
     */
    public static String encodeBase62(byte[] input) {
        char[] chars = new char[input.length];
        for (int i = 0; i < input.length; i++) {
            chars[i] = BASE62[((input[i] & 0xFF) % BASE62.length)];
        }
        return new String(chars);
    }

    /**
     * Html 转码.
     */
    public static String escapeHtml(String html) {
        return StringEscapeUtils.escapeHtml4(html);
    }

    /**
     * Html 解码.
     */
    public static String unescapeHtml(String htmlEscaped) {
        return StringEscapeUtils.unescapeHtml4(htmlEscaped);
    }

    /**
     * Xml 转码.
     */
    public static String escapeXml(String xml) {
        return StringEscapeUtils.escapeXml10(xml);
    }

    /**
     * Xml 解码.
     */
    public static String unescapeXml(String xmlEscaped) {
        return StringEscapeUtils.unescapeXml(xmlEscaped);
    }

    /**
     * URL 编码, Encode默认为UTF-8.
     */
    public static String urlEncode(String part) {
        try {
            return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw Exceptions.unchecked(e);
        }
    }

    /**
     * URL 解码, Encode默认为UTF-8.
     */
    public static String urlDecode(String part) {

        try {
            return URLDecoder.decode(part, DEFAULT_URL_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw Exceptions.unchecked(e);
        }
    }


    public static String escapeJava(String part) {
        return StringEscapeUtils.escapeJava(part);
    }
}
